package com.hzlj.position.locate.differentiation.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fz.common.base.core.AddressResolutionUtil;
import com.fz.common.base.dto.AddressDTO;
import com.google.common.collect.Maps;
import com.hzlj.common.message.common.dto.message.MessageNoticeUserDTO;
import com.hzlj.common.message.common.util.MessageRestUtil;
import com.hzlj.position.config.common.enums.WarningType;
import com.hzlj.position.config.service.NoticeConfigService;
import com.hzlj.position.locate.common.model.Position;
import com.hzlj.position.locate.differentiation.DifferentiationService;
import com.hzlj.sqjz.jz.cache.JzJbxxCache;
import com.hzlj.sqjz.jz.common.dto.common.JzJbxxCacheDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PositionWarningNoticeGzry {
    @Resource
    private NoticeConfigService noticeConfigService;
    @Resource
    private JzJbxxCache jzJbxxCache;

    public void notice(List<Position> positions,
                       DifferentiationService differentiationService) {
        for (Position position : positions) {
            if (!noticeConfigService.warningGzryNotice(position.getJgCode(), position.getWarningType())) {
                continue;
            }
            try {
                JzJbxxCacheDTO jzry = jzJbxxCache.getJzJbxxByJzId(position.getJzId());
                String messageTemplate = "position-warning-" + position.getWarningType() + "-gzry";
                Map<String, Object> params = Maps.newHashMap();
                params.put("jzryXm", position.getXm());
                params.put("jzrySjh", jzry.getSjh());
                params.put("warningTypeText", WarningType.of(position.getWarningType()).getText());
                params.put("positionTime", DateUtil.formatDateTime(position.getPositionTime()));
                //位置信息
                if (ObjectUtil.isNotEmpty(position.getPosition())) {
                    AddressDTO address = AddressResolutionUtil.addressResolution(position.getPosition());
                    if (address != null) {
                        params.put("positionFmt", address.getProvince() + address.getCity() + address.getCounty());
                    }
                }
                MessageRestUtil.noticeQueryUsers(
                        messageTemplate,
                        position.getId(),
                        params,
                        MessageNoticeUserDTO.of(true, position.getJgCode(), differentiationService.getNoticeWorkerRoles())
                );
            } catch (Exception e) {
                log.error("发送定位告警消息失败[通知工作人员]报错:{}", position, e);
            }
        }
    }
}
